<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <!-- <crudOperation :permission="permission" /> -->
      <div style="display: flex;align-items: start;margin: 0 0 20px 0;gap: 10px;">
        <el-radio-group v-model="selected">
          <el-radio-button label="按料号设置" value="PRODUCTNO" />
          <el-radio-button label="按客户设置" value="RECEIVER" />
          <el-radio-button label="按类型设置" value="CATEGORY" />
        </el-radio-group>
        <crudOperation :permission="permission" :right-operation="true">
          <el-upload
            ref="uploadRef"
            slot="right"
            class="filter-item"
            :headers="headers"
            :action="uploadUrl"
            :limit="1"
            :show-file-list="false"
            :http-request="customUpload"
          >
            <el-button
              type="success"
              plain
              icon="el-icon-upload2"
              size="mini"
              :loading="btn.upload"
              @click="handleUpload"
            >批量上传</el-button>
          </el-upload>
          <el-button
            slot="right"
            type="primary"
            size="mini"
            class="filter-item"
            icon="el-icon-download"
            plain
            :loading="btn.download"
            @click="downloadExcel"
          >下载模板</el-button>
        </crudOperation>
      </div>
      <!--表单组件-->
      <el-dialog :close-on-click-modal="false" :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0" :title="crud.status.title" width="500px">
        <el-form ref="form" :model="form" size="small" label-width="140px">
          <el-form-item label="料号">
            <el-input v-model="form.productNo" style="width: 250px;" />
          </el-form-item>
          <el-form-item label="规则类型">
            <el-input v-model="form.ruleType" :readonly="true" style="width: 250px;" />
          </el-form-item>
          <el-form-item label="客户">
            <el-input v-model="form.receiverName" style="width: 250px;" />
          </el-form-item>
          <el-form-item label="客户物料编码">
            <el-input v-model="form.partnerProductNo" style="width: 250px;" />
          </el-form-item>
          <el-form-item label="物料类型">
            <el-select v-model="form.category" filterable placeholder="请选择" style="width: 250px;">
              <el-option
                v-for="item in dict.limitmaterial_type"
                :key="item.id"
                :label="item.label"
                :value="Number(item.value)"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="物料描述">
            <el-input v-model="form.productDescription" style="width: 250px;" />
          </el-form-item>
          <el-form-item label="上限">
            <el-input v-model="form.maxLimit" style="width: 250px;" />
          </el-form-item>
          <el-form-item label="下限">
            <el-input v-model="form.minLimit" style="width: 250px;" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="crud.cancelCU">取消</el-button>
          <el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
        </div>
      </el-dialog>
      <!--表格渲染-->
      <el-table ref="table" v-loading="crud.loading" :data="crud.data" size="small" style="width: 100%;" @selection-change="crud.selectionChangeHandler">
        <!-- <el-table-column type="selection" width="55" /> -->
        <el-table-column prop="ruleType" label="规则类型" />
        <el-table-column v-if="selected === '按料号设置'" prop="productNo" label="料号" />
        <el-table-column prop="receiverName" label="客户" />
        <el-table-column prop="partnerProductNo" label="客户物料编码" />
        <el-table-column v-if="selected !== '按客户设置'" prop="category" label="物料类型" />
        <el-table-column v-if="selected === '按料号设置'" prop="productDescription" label="物料描述" />
        <el-table-column prop="maxLimit" label="上限" />
        <el-table-column prop="minLimit" label="下限" />
        <el-table-column label="操作" width="150px" align="center">
          <template slot-scope="scope">
            <!-- <udOperation
              :data="scope.row"
              :permission="permission"
            /> -->
            <el-button v-permission="permission.edit" :loading="crud.status.cu === 2" size="mini" type="primary" icon="el-icon-edit" @click.stop="crud.toEdit(scope.row)" />
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination />
    </div>
  </div>
</template>

<script>
import { getToken } from '@/utils/auth'
import crudInventoryLimit from '@/api/work/inventoryLimit'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import pagination from '@crud/Pagination'
import crudOperation from '@crud/CRUD.operation'

const defaultForm = { id: null, ruleType: null, productNo: null, receiverName: null, partnerProductNo: null, category: null, productDescription: null, maxLimit: null, minLimit: null, createTime: null, updateTime: null, createName: null }
export default {
  name: 'InventoryLimit',
  components: { pagination, crudOperation },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  cruds() {
    return CRUD({ title: 'inventoryLimit', url: 'api/inventoryLimit', idField: 'id', sort: 'id,desc', crudMethod: { ...crudInventoryLimit },
      queryOnPresenterCreated: false,
      optShow: {
        add: true,
        edit: false,
        del: false,
        reset: true,
        download: true
      }
    })
  },
  dicts: ['rule_type', 'material_type', 'limitmaterial_type'],
  data() {
    return {
      permission: {
        add: ['admin', 'inventoryLimit:add', 'otherUser'],
        edit: ['admin', 'inventoryLimit:edit', 'otherUser'],
        del: ['admin', 'inventoryLimit:del', 'otherUser']
      },
      rules: {
      },
      selected: '按料号设置',
      uploadUrl: process.env.VUE_APP_BASE_API + 'api/materialMaintenance/importExcel' + `/ruleType=${this.selectedValue}`,
      headers: {
        'Authorization': getToken(),
        'Content-Type': 'multipart/form-data'
      },
      fileName: '',
      btn: {
        upload: false,
        download: false
      }
    }
  },
  computed: {
    selectedValue() {
      switch (this.selected) {
        case '按客户设置':
          return 'RECEIVER'
        case '按类型设置':
          return 'CATEGORY'
        case '按料号设置':
          return 'PRODUCTNO'
        default:
          return ''
      }
    }
  },
  watch: {
    selectedValue(newVal, oldVal) {
      if (newVal === 'RECEIVER') {
        this.query.ruleType = 'RECEIVER'
        this.crud.toQuery()
      } else if (newVal === 'CATEGORY') {
        this.query.ruleType = 'CATEGORY'
        this.crud.toQuery()
      } else if (newVal === 'PRODUCTNO') {
        this.query.ruleType = 'PRODUCTNO'
        this.crud.toQuery()
      }
    },
    'crud.status.add'(newVal, oldVal) {
      if (newVal === 1) {
        switch (this.selected) {
          case '按客户设置':
            this.form.ruleType = 'RECEIVER'
            break
          case '按类型设置':
            this.form.ruleType = 'CATEGORY'
            break
          case '按料号设置':
            this.form.ruleType = 'PRODUCTNO'
            break
        }
      }
    }
  },
  created() {
    this.query.ruleType = 'PRODUCTNO'
    this.crud.toQuery()
  },
  mounted() {
  },
  methods: {
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      return true
    },
    // 自定义上传
    async customUpload(file) {
      try {
        this.btn.upload = true
        const formData = new FormData()
        formData.append('file', file.file)
        const res = await crudInventoryLimit.uploadFileAPI({
          formData: formData,
          ruleType: this.selectedValue
        })
        if (res.result === 'OK') {
          this.$message.success(res.message)
        } else {
          this.$message.warning(res.data)
        }
      } finally {
        this.btn.upload = false
      }
    },
    // 清除已选择的文件
    handleUpload() {
      this.$refs.uploadRef.clearFiles() // 清除已选择的文件
      this.$refs.uploadRef.submit() // 重新提交上传
    },
    async downloadExcel() {
      try {
        this.btn.download = true
        const res = await crudInventoryLimit.downloadFileAPI(this.selectedValue)
        if (res && res instanceof Blob) {
          this.downloadFile(res)
        } else {
          this.$message.warning('文件下载失败，返回数据不是有效的文件内容')
        }
      } finally {
        this.btn.download = false
      }
    },
    // 解析excel文件
    downloadFile(obj) {
      const url = window.URL.createObjectURL(new Blob([obj]))
      const link = document.createElement('a')
      link.style.display = 'none'
      link.href = url
      if (this.selected === '按客户设置') {
        this.fileName = `库存上下限客户模板表_${new Date().getTime()}.xlsx`
      } else if (this.selected === '按类型设置') {
        this.fileName = `库存上下限类型模板表_${new Date().getTime()}.xlsx`
      } else if (this.selected === '按料号设置') {
        this.fileName = `库存上下限料号模板表_${new Date().getTime()}.xlsx`
      }
      link.setAttribute('download', this.fileName)
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      window.URL.revokeObjectURL(url)
    }
  }
}
</script>

<style scoped>

</style>
